<template>
  <div>
<el-form :model="step" ref="form" label-width="100px" :rules="rules">
    <el-form-item label="步骤名称" prop="name">
      <el-input v-model="step.name"></el-input>
    </el-form-item>
    <el-form-item label="数据选择">
      <el-row style="padding-right: 20px">
      <el-col :span="14">
        <el-select v-model="step.connection" :value="step.connection" placeholder="数据源">
          <el-option v-for="source in dataSource.sourceList" :label="source.name" :value="source.id"></el-option>
        </el-select>
      </el-col>
      <el-col :span="2" style="margin-right: 8px"><el-button :disabled="true" v-show="dbType != ''">{{dbType}}</el-button></el-col>
      <el-col :span="2" :offset="3">
        <el-button type="primary" @click="showSqlBuild" icon="setting" >导入表</el-button>
      </el-col>
      </el-row>
    </el-form-item>

    <el-form-item label="sql" >
      <el-input type="textarea" v-model="step.sql" class="sql11" :rows="14" resize="none">
      </el-input>
    </el-form-item>

  <el-form-item label="记录数量限制">
    <el-row style="padding-right: 20px">
    <el-col :span="13">
    <el-input-number v-model="step.limit" :step="1000" :min="0"></el-input-number>
    </el-col>
    <el-col :span="2" :offset="6">
      <el-button type="info" @click="testSQL">测试SQL</el-button>
    </el-col>
   </el-row>
  </el-form-item>


  <el-form-item label="">
    <el-col :span="6"><el-checkbox v-model="step.lazy_conversion_active" true-label="Y" false-label="N">简易转换</el-checkbox>
    </el-col>
    <el-col :span="7"><el-checkbox v-model="step.variables_active" true-label="Y" false-label="N">替换SQL语句里的变量</el-checkbox>
    </el-col>
    <el-col :span="7">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp<!--<el-checkbox v-model="step.execute_each_row" true-label="Y" false-label="N">执行每一行</el-checkbox>-->
    </el-col>
  </el-form-item>
 </el-form>

    <el-dialog title="导入表" v-model="isShow" size="small" :modal="false" :close-on-click-modal="false">

    <el-tabs active-name="table" @tab-click="tabClickHandler">
      <el-tab-pane label="数据表" name="table">
        <el-row :gutter="10">
          <el-col  :md="{span:12}" :xs="{span:24}">
        <el-table :data="dataSource.tables" border max-height="340" @selection-change="handleSelectionChange" :row-style="setRowColor">
          <el-table-column type="selection" ></el-table-column>
          <el-table-column prop="name" label="表名"></el-table-column>
          <el-table-column prop="cnname" label="中文名"></el-table-column>
          <el-table-column label="字段">
            <template scope="scope">
              <el-button  @click="showSetFields(scope.row,scope.$index)" size="mini" type="info">配置</el-button>
            </template>
          </el-table-column>
        </el-table>
          </el-col>

          <el-col :md="{span:12}" :sm="{span:24}">
            <div id="fieldBox" class="fieldBox" :class="{maxHeight:fieldBoxMaxHeight}" v-show="curEditTable.fields.length > 0">
              <el-checkbox :indeterminate="curEditTable.isIndeterminate" v-model="curEditTable.selectedAllFields" @change="handleCheckAllChange">全选</el-checkbox>
              <div style="margin: 15px 0;border-bottom: solid;border-width : 1px;border-bottom-color : #E5E9F2;"></div>
              <el-checkbox-group v-model="curEditTable.selectedFields" @change="handleCheckedCitiesChange">
                <div  v-for="field in curEditTable.fields"><el-checkbox :label="field">
                  <span class="field" :class="{pk:field.pk==1}">
                    <table>
                      <tr>
                        <td style="width: 100px">{{field.name}}</td>
                        <td style="width: 100px">{{field.cnname?field.cnname:""}}</td>
                        <td style="width: 90px">{{field.type}}</td>
                      </tr>
                    </table>
                  </span>

                </el-checkbox></div>
              </el-checkbox-group>
            </div>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="联接关系" name="join" :disabled="selectedTableSize < 2">
        <el-table :data="step.ext.joins" border style="width:100%" height="200" :row-style="setRowColor2">
          <el-table-column prop="parent" label="主表"  width="220"  >
            <template scope="scope">
              <div v-if="scope.$index == joinsConditions.rowIndex">
                  {{scope.row.parent.name}}
              </div>
              <div v-else>
                <el-select v-model="scope.row.parent" filterable placeholder="请选择" size="mini">
                  <el-option v-for="t in step.ext.tables" :value="t" :label="t.name + '|' +t.cnname"></el-option>
                </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="joinType" label="联接类型" width="152">
            <template scope="scope">
              <el-select v-model="scope.row.joinType" size="mini">
                <el-option
                  v-for="type in step.ext.jointype"
                  :value="type">
                </el-option>
              </el-select>
            </template>

          </el-table-column>
          <el-table-column prop="client" label="子表"  width="220"  >
            <template scope="scope">
              <div v-if="scope.$index == joinsConditions.rowIndex">
                {{scope.row.client.name}}
              </div>
              <div v-else>
              <el-select v-model="scope.row.client" filterable placeholder="请选择" size="mini">
                <el-option v-for="t in step.ext.tables" :value="t" :label="t.cnname?t.name + '|' +t.cnname:t.name"></el-option>
              </el-select>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="140">
            <template scope="scope">

              <div v-show="scope.$index != joinsConditions.rowIndex">
                <el-row>
                  <el-col :span="8">
              <el-tooltip class="item" effect="dark" content="设置关联条件" placement="right">
                <el-button  icon="setting" size="mini" @click="setJoinConditions(scope.row,scope.$index)"/>
              </el-tooltip>
                  </el-col>
                  <el-col :span="8">
              <el-button  icon="plus" size="mini" @click="joinsPlusHandle(scope.$index)"/>
                  </el-col>
                  <el-col :span="8">
              <el-button  icon="minus" size="mini" @click="joinsMinusHandle(scope.$index)"/>
                  </el-col>
                </el-row>
              </div>

            </template>
          </el-table-column>
        </el-table>
        <el-row><el-col :span="24"><div class="line"><!--华丽的分隔线--></div></el-col></el-row>
        <el-row :gutter="8">
          <el-col :span="16">
            <el-input v-model="joinsConditions.curRow.logic">
              <template slot="prepend">逻辑 </template>
            </el-input>
          </el-col>
          <el-col :lg="{span:3}" :md="{span:6}" :sm="{span:8}" :xs="{span:8}">
          <div>
            <el-row>
          <el-col :span="12">
            <el-button  @click="conditionsPlusHandle" icon="plus" type="primary"/>
          </el-col>
          <el-col :span="12">
            <el-tooltip v-if="joinsConditions.curRow.parent" class="item" effect="dark" content="确认关联条件" placement="right">
            <el-button icon="check" type="success" @click="reSetJoinsConditions"/>
            </el-tooltip>
          </el-col>
            </el-row>
          </div>
          </el-col>
        </el-row>
        <el-row><el-col :span="24"><div class="line"><!--华丽的分隔线--></div></el-col></el-row>
        <el-table :data="joinsConditions.curRow.conditions" border style="width:100%" height="200" >
          <el-table-column prop="index" width="30">
            <template scope="scope">
              {{scope.row.index}}
            </template>
          </el-table-column>
          <el-table-column prop="field" label="主表字段" width="190">
            <template scope="scope">
              <el-select v-model="scope.row.field" size="mini">
                <el-option
                  v-for="f in joinsConditions.parentFields"
                  :value="f.name">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="cndType" label="条件" width="150">
            <template scope="scope">
              <el-select v-model="scope.row.cndType" size="mini">
                <el-option
                  v-for="type in joinsConditions.condition"
                  :value="type">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="子表字段" width="220">
            <template scope="scope">
              <el-select v-model="scope.row.value" size="mini">
                <el-option
                  v-for="f in joinsConditions.clientFields"
                  :value="f.name">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            width="140">
            <template scope="scope">
              <el-button type="danger" size="mini" @click="conditionsMinusHandle(scope.row.index,scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row><el-col :span="24"><div class="line"><!--华丽的分隔线--></div></el-col></el-row>
      </el-tab-pane>

    </el-tabs>
    <span slot="footer" class="dialog-footer">
           <el-button @click="isShow = false">取 消</el-button>
           <el-button type="primary" @click="buildSql">导入表</el-button>
     </span>
  </el-dialog>
  </div>
</template>

<style scoped>
  .line{
    border-bottom-color : #D3DCE6;
    border-width : 2px;
    border-bottom-style : dashed;
    margin:4px 0
  }
  .fieldBox{
    padding: 10px 10px;
    border: 1px solid #eaeefb;
    border-radius: 4px;
    transition: 0.2s;
    overflow: auto;
  }
  .maxHeight{
    height: 340px;
  }
  .field{
    width: 200px;
    padding-left: 18px;
    float: right;
    display: block;
  }
  .field.pk{
      background: url("../../assets/steps/keySmall.png") 0 0/16px 16px no-repeat;
  }


</style>
<script>
  import {Steps,DataSource} from "../../model/DataModel";
  import HttpRequest from "../../model/HttpRequset";
  import StepCommon from "./mixins/StepMixin";
  import cloneDeep from "lodash/cloneDeep";
  export default {
    mixins: [StepCommon],
    watch: {
      'step.connection'(newVal){//数据源变化，更新表数据
        let that = this;
        if (newVal&&typeof newVal!="object") {
          HttpRequest.requestSourceInstanceById(newVal).then(function (response) {
            that.dbType = that.dbTypeMap[newVal];
            that.dataSource.tables = response.data;
            for (let i in that.dataSource.tables) {
              let table = that.dataSource.tables[i];
              table.selectedFields = [];
              table.isIndeterminate = false;
              table.selectedAllFields = false;
              for (let j in table.columnList) {
                let cl = table.columnList[j];
                cl.selected = false;
              }
            }
          });
        }
      },
      'step.ext.tables'(newVal){
          this.selectedTableSize = newVal.length;
          if(this.selectedTableSize>1) { //配置了join后，又回去折腾表选择，清除影响到的join
            let joins = this.step.ext.joins;
            let joinsFilter = joins.filter((join) => {
              return newVal.includes(join.parent) && newVal.includes(join.client);
            });
            this.step.ext.joins = joinsFilter;
          }
      }
    },
    mounted () {
      //开始初始化数据
      // 获取数据源-S
      let that = this;
      HttpRequest.requestSourceList().then(function (response) {
          let ds = response.data.ds;
          that.dataSource.sourceList = ds;
          ds.forEach((item)=>{
            that.dbTypeMap[item.id] = item.dbType;
          });
      }, function (response) {

      });

      this.joinsConditions.condition = this.step.ext.conditiontype;
      //结束初始化数据
    },
    data(){
      return {
        step: Steps.TableInput({name: "", x: 120, y: 20}),
        dataSource: DataSource(),
        joinsConditions:{parentFields:[],condition:[],clientFields:[],curRow:{},rowIndex:-1},
        isShow: false,
        selectedTableSize:0,//用于控制sql构建界面的显示
        curEditTable:{table:{},fields:[],selectedFields:[],isIndeterminate:false,selectedAllFields:false},
        curRowIndex:"",
        fieldBoxMaxHeight:false,
        dbType:"",
        dbTypeMap:{},
        rules: {
          connection: [
            {required: true, message: '请选择数据源', trigger: 'change'},
          ]
        }
      }
    },
    methods: {
      showSqlBuild(){
        this.isShow = true;
      },
      handleSelectionChange(val){
        this.step.ext.tables = val;
      },
      setJoinConditions(row,index){
          let parent = row.parent;
          let client = row.client;
          if(parent ==""||client==""){
              this.warning("请先选择主表和子表，再设置关联条件");
              return;
          }
         this.joinsConditions.parentFields =cloneDeep(parent.selectedFields);
         this.joinsConditions.clientFields = cloneDeep(client.selectedFields);
         this.joinsConditions.curRow = row;
        this.joinsConditions.rowIndex = index;
      },
      conditionsPlusHandle(){
         let cndItem = Steps.TableInput().ext.joins[0].conditions[0];
         let curRow = this.joinsConditions.curRow;
         let len = curRow.conditions.length-1;
         let newIndex = curRow.conditions[len].index+1;
         cndItem.index = newIndex;
            curRow.conditions.push(cndItem);
            curRow.logic = this.logicHandle();
      },
      conditionsMinusHandle(index,arrayIndex){
          if(index == 0){
              this.warning('首行数据不能删除！');
          }else{
              let curRow = this.joinsConditions.curRow;
                  curRow.conditions.splice(arrayIndex,1);
              if(curRow.conditions.length == 1){
                curRow.logic = '#0';
              }else{
                curRow.logic = this.logicHandle();
              }
          }
      },
      logicHandle(){
        let conditions = this.joinsConditions.curRow.conditions;
        const pre = "#";
        let logic = "";
        conditions.forEach((condition)=>{
          let index = condition.index,
               item = "";
          item = item.concat(pre,index);
          if(logic == ""){
            logic = item;
          }else{
            logic = logic.concat(" and ",item);
          }
        });
        return logic;
      },
      joinsPlusHandle(index){
        let join = Steps.TableInput().ext.joins[0];
        this.step.ext.joins.push(join);
      },
      joinsMinusHandle(index){
        if(index == 0){
          this.$message({
            message: '首行数据不能删除！',
            type: 'warning'
          });
        }else{
          this.step.ext.joins.splice(index,1);
        }
      },
      buildSql(){
          let that = this;
          let dsId = this.step.connection
          if(this.selectedTableSize > 1){//join
            if(this.checkJoinsData()) {
              HttpRequest.tableInputGetSql(that.step.ext.joins,dsId).then(function (response) {
                let data = response.data;
                that.step.sql = data.sql;
                  that.step.outputFields = data.fields;
              }, function (response) {

              });
            }else{
                this.warning("请检查，关联信息设置不完整");
                return;
            }

          }else if(this.selectedTableSize == 1){
            let table = that.step.ext.tables[0], noFieldSelected = true, fields = table.columnList;
            for(let i in fields){
                if(fields[i].selected == true){
                  noFieldSelected = false;
                  break;
                }
            }
            if(noFieldSelected){
              this.warning('最少要选择一个字段');
              return;
            }
            HttpRequest.tableInputGetSimpleSql(table,dsId).then(function (response) {
              let data = response.data;
              that.step.sql = data.sql;
                that.step.outputFields = data.fields;
            }, function (response) {

            });
          }else{
            this.warning('构建SQL，最少要选一张表');
            return;
          }
        this.isShow = false
      },
      showSetFields(table,index){
        let t = this.curEditTable;
        t.table = table;
        t.fields = table.columnList;
        let selectedAllFields = table.selectedAllFields,
        selectedFields    = table.selectedFields,
        isIndeterminate   = table.isIndeterminate;
        t.selectedAllFields = selectedAllFields;
        t.isIndeterminate   = isIndeterminate;
        t.selectedFields    = selectedFields;
        this.curRowIndex = index;
        if(t.fields&&t.fields.length>9){
            this.fieldBoxMaxHeight = true;
        }else{
          this.fieldBoxMaxHeight = false;
        }
      },
      sycTable(){
        let table               = this.curEditTable.table;
        table.selectedFields    = this.curEditTable.selectedFields;
        table.selectedAllFields = this.curEditTable.selectedAllFields;
        table.isIndeterminate   = this.curEditTable.isIndeterminate;
      },
      handleCheckAllChange(event) {
        let checked = event.target.checked;
        this.curEditTable.selectedFields = checked ? this.curEditTable.fields : [];//赋值
        this.curEditTable.selectedAllFields = checked; //全选
        this.curEditTable.isIndeterminate = false; //处理部分选择图标
        let fields = this.curEditTable.fields;
        for(let i in fields){
            fields[i].selected = checked;
        }
        this.sycTable();
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.curEditTable.selectedAllFields = checkedCount === this.curEditTable.fields.length;
        this.curEditTable.isIndeterminate = checkedCount > 0 && checkedCount < this.curEditTable.fields.length;
        let fields = this.curEditTable.fields;
        for(let i in fields){
          fields[i].selected = false;
        }
        for(let i in value){
            value[i].selected = true;
        }
        this.sycTable();
      },
      setRowColor(row,index){
          if(index == this.curRowIndex) {
            return {"background-color": " #e2f0e4"};
          }else{
            return {};
          }
      },
      setRowColor2(row,index){
        if(index == this.joinsConditions.rowIndex) {
          return {"background-color": " #e2f0e4"};
        }else{
          return {};
        }
      },
      tabClickHandler(tab){
        this.reSetJoinsConditions();
          if(tab.name == "join"){
            let joins = this.step.ext.joins;
            if(joins.length < 1){
                joins.push({"parent": "", "client": "", "joinType": "INNER JOIN",
                  "conditions": [{"field": "", "cndType": "=", "value": "", "index": 0}],
                  "logic": "#0"
                });
            }
          }
      },
      reSetJoinsConditions(){
          this.joinsConditions = {parentFields:[],condition:this.step.ext.conditiontype,clientFields:[],curRow:{},rowIndex:-1};
      },
      checkJoinsData(){
           let joins  = this.step.ext.joins;
           if(joins.length < 1){
               return false;
           }
          for(let i in joins){
              let join = joins[i];
            if(join.parent==""||join.client==""){
              return false;
            }
            let conditions = join.conditions;
            for(let i in conditions){
                let condition = conditions[i];
              if(condition.field==""||condition.value==""){
                return false;
              }
            }
          }
          return true;
      },
      testSQL(){
          let sql = this.step.sql;
        if(!this.step.connection){
          this.warning("数据源不能为空");
          return;
        }
        if(!sql){
            this.warning("sql 语句不能为空");
            return;
        }
        sql = sql.toUpperCase();
        if((sql.indexOf("SELECT")==-1)||(sql.indexOf("FROM")==-1)){
          this.warning("sql 语句最小包含Select 和 from 关键字");
          return;
        }
        let that = this;
        return HttpRequest.testSql(that.step.sql,that.step.connection).then(function (response) {
          let data = response.data;
          if("success"==data.code){
            that.step.outputFields = data.data.fields;
            that.success("SQL 语句运行测试通过");
          }else{
            that.notify("SQL 测试异常");
          }
        }, function (response) {
          that.notify("SQL 测试异常");
        });
      }
    }
  }
</script>
